package com.csust.automaticteach.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csust.automaticteach.common.BaseResponse;
import com.csust.automaticteach.common.ResultUtils;
import com.csust.automaticteach.model.dto.classes.classExercise.AddClassExerciseRequest;
import com.csust.automaticteach.model.enums.GenerateQuestionStatusEnum;
import com.csust.automaticteach.exception.BusinessException;
import com.csust.automaticteach.exception.ErrorCode;
import com.csust.automaticteach.exception.ThrowUtils;
import com.csust.automaticteach.model.dto.generateexam.AddGenerateExamRequest;
import com.csust.automaticteach.model.dto.generateexam.GenerateExamEditDTO;
import com.csust.automaticteach.model.dto.generateexam.GenerateExamQueryDTO;
import com.csust.automaticteach.model.entity.Classes;
import com.csust.automaticteach.model.entity.GenerateExam;
import com.csust.automaticteach.model.entity.User;
import com.csust.automaticteach.model.vo.exercises.GenExercisesVO;
import com.csust.automaticteach.model.vo.generateexam.GenerateExamPageVO;
import com.csust.automaticteach.model.vo.generateexam.GenerateExamVO;
import com.csust.automaticteach.model.vo.generateteach.UploadReturnVO;
import com.csust.automaticteach.service.ClassesService;
import com.csust.automaticteach.service.GenerateExamService;
import com.csust.automaticteach.service.UserService;
import com.csust.automaticteach.utils.template.generate.ExamGenerator;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import static com.csust.automaticteach.constant.ExceptionConstant.ONLY_ONE_REFERENCE_ALLOWED;
import static com.csust.automaticteach.constant.FileConstant.FILE_CAN_NOT_BE_NULL;

/**
 * @ClassNameGenerateExamController
 * @Description TODO
 * @Author钰玟
 * @Date2025/7/7 下午7:01
 * @Version 1.0
 **/
@RestController
@RequestMapping("/generateExam")
@Slf4j
public class GenerateExamController {

    @Resource
    private UserService userService;
    @Resource
    private GenerateExamService generateExamService;
    @Resource
    private ClassesService classesService;
    @Resource
    private ExamGenerator examGenerator;


    @PostMapping("/upload")
    @Deprecated //uploadReferenceFile 已改为前端上传文件直接解析为文本reference
    public BaseResponse<UploadReturnVO> uploadReferenceFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        // 校验文件
        ThrowUtils.throwIf(file.isEmpty(), ErrorCode.PARAMS_ERROR, FILE_CAN_NOT_BE_NULL);
        // 获取登录用户
        User loginUser = userService.getLoginUser(request);
        UploadReturnVO uploadReturnVO = generateExamService.uploadReferenceFile(file, loginUser);
        return ResultUtils.success(uploadReturnVO);
    }

    @PostMapping("/add")
    @Deprecated //统一接口在GenerateExercisesController中      @PostMapping("/exam/add")
    public BaseResponse<GenExercisesVO> addGenerateExam(@RequestBody AddGenerateExamRequest addGenerateExamRequest
            , HttpServletRequest request) {
        //1.1 生成测试Id  已改为 前端上传文件直接解析为文本reference
//        Long id = addGenerateExamRequest.getId();
        Long id = 1L;//保证不报错
        //大纲id
        Long generateTeachId = addGenerateExamRequest.getGenerateTeachId();
        //知识点
        String knowledgePoint = addGenerateExamRequest.getKnowledgePoint();
        //校验参数  仅允许选择一个参考材料
        ThrowUtils.throwIf(id != null && (generateTeachId != null || knowledgePoint != null)
                , ErrorCode.PARAMS_ERROR, ONLY_ONE_REFERENCE_ALLOWED);
        if (generateTeachId != null && StrUtil.isNotBlank(knowledgePoint)) {
            ThrowUtils.throwIf(true, ErrorCode.PARAMS_ERROR, ONLY_ONE_REFERENCE_ALLOWED);
        }
        User loginUser = userService.getLoginUser(request);
//        List<GenerateExamVO> generateExamVOList = generateExamService.addGenerateExamSyn(addGenerateExamRequest, loginUser);
        //重构
//        List<Exercises> exercisesList = generateExamService.addGenerateExamSynRefactoring(addGenerateExamRequest, loginUser);
        //模板方法
        GenExercisesVO genExercisesVO = examGenerator.generate(addGenerateExamRequest, loginUser);
        return ResultUtils.success(genExercisesVO);
    }

    /**
     * 获取课程大纲列表
     *
     * @param generateExamQueryDTO 查询参数
     * @param request              请求
     * @return
     */
    @PostMapping("/list/page/vo")
    @Deprecated      //统一接口在GenerateExercisesController中      @PostMapping("/exam/list/page")
    public BaseResponse<Page<GenerateExamPageVO>> listGenerateExamVOByPage(@RequestBody GenerateExamQueryDTO generateExamQueryDTO
            , HttpServletRequest request) {
        ThrowUtils.throwIf(generateExamQueryDTO == null, ErrorCode.PARAMS_ERROR);
        // 获取分页相关数据
        long current = generateExamQueryDTO.getCurrent();
        long pageSize = generateExamQueryDTO.getPageSize();

        //
        User loginUser = userService.getLoginUser(request);
        generateExamQueryDTO.setUserId(loginUser.getId());
        //分页查询
        Page<GenerateExam> generateExamPage = generateExamService.page(new Page<>(current, pageSize),
                generateExamService.getGenerateExamQueryWrapper(generateExamQueryDTO));
        Page<GenerateExamPageVO> generateExamPageVOPage = new Page<>(current, pageSize, generateExamPage.getTotal());
        List<GenerateExamPageVO> generateExamVOList = generateExamService.getGenerateExamVOList(generateExamPage.getRecords());
        generateExamPageVOPage.setRecords(generateExamVOList);
        return ResultUtils.success(generateExamPageVOPage);
    }

    /**
     * 获取某个详情的生成测试
     *
     * @param id 对应id
     * @return
     */
    @GetMapping("/get/{id}")
    @Deprecated // 统一接口在GenerateExercisesController中          @GetMapping("/exam/get")
    public BaseResponse<List<GenerateExamVO>> getGenerateExamVO(@PathVariable("id") Long id) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        GenerateExam generateExam = generateExamService.getById(id);
        List<GenerateExamVO> generateExamVO = generateExamService.getGenerateExamVO(generateExam);
        ThrowUtils.throwIf(generateExam == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(generateExamVO);
    }

    /**
     * 修改生成测试
     *
     * @param generateExamEditDTO dto
     * @return boolean
     */
    @PostMapping("/edit")
    @Transactional //开启事务
    public BaseResponse<Boolean> updateGenerateExam(@RequestBody GenerateExamEditDTO generateExamEditDTO
            ,HttpServletRequest  request) {
        //查看是否为空
        if (generateExamEditDTO == null || generateExamEditDTO.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        GenerateExam generateExam = new GenerateExam();
        //json化题目列表作为content
        List<GenerateExamVO> generateExamVOList = generateExamEditDTO.getGenerateExamVOList();
        String content = JSONUtil.toJsonStr(generateExamVOList);
        generateExam.setContent(content);
        Long id = generateExamEditDTO.getId();
        String title = generateExamEditDTO.getTitle();
        Integer status = generateExamEditDTO.getStatus();
        if(Objects.equals(status, GenerateQuestionStatusEnum.PUBLISHED.getValue())){
            //如果是发布
            //发布到其班级
            //1.先获取该老师下的班级 TODO
            User loginUser = userService.getLoginUser(request);
            QueryWrapper<Classes> queryWrapper = new QueryWrapper<Classes>().eq("headTeacher", loginUser.getId());
            Classes classes =  classesService.getBaseMapper().selectOne(queryWrapper);
            //添加班级测试
            AddClassExerciseRequest addClassExerciseRequest = new AddClassExerciseRequest();
            addClassExerciseRequest.setClassId(classes.getId());
            addClassExerciseRequest.setExercisesSetsId(id);
            addClassExerciseRequest.setPublishTeacher(loginUser.getId());
            Long classExerciseId = classesService.addClassExam(addClassExerciseRequest);
            ThrowUtils.throwIf(classExerciseId < 0, ErrorCode.OPERATION_ERROR);
        }
        generateExam.setId(id);
        generateExam.setTitle(title);
        generateExam.setStatus(status) ;
        //设置修改时间
        generateExam.setUpdateTime(new Date());
        //使用saveOrUpdate
        boolean result = generateExamService.saveOrUpdate(generateExam);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
}
